package org.scboy.dbms;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.scboy.dbms.service.BaseAppServerService;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 服务启动失败
 */
@Configuration
@Order(Ordered.LOWEST_PRECEDENCE)
public class ServerStartFailed implements ApplicationListener<ApplicationFailedEvent>{

	Log log=LogFactory.get();
	
	@Value("${spring.application.name}")
	private String appName="";

	@Value("${server.port}")
	int port;

	@Autowired
	BaseAppServerService service;
	
	@Override
	public void onApplicationEvent(ApplicationFailedEvent event) {
		Throwable t = event.getException();
		String ip="";
		try {
			InetAddress localHost=InetAddress.getLocalHost();
			ip=localHost.getHostAddress();
		} catch (UnknownHostException e) {
			log.error("无法获取服务器IP地址",e);
		}
		String serverId=MD5.create().digestHex(appName+"_"+ip+":"+port);
		service.update(Model.create().add("id", serverId).add("status", 0).add("serverMsg", ExceptionUtil.stacktraceToString(t)));
		log.error("微服务启动失败。");
	}
}
